let ajaxTimes = 0;
let app = getApp()
export const request= async (params)=>{
  const token = wx.getStorageSync('token')
  // const baseUrl = app.globalData.baseUrl
  let domain = app.globalData.domain
  // console.log(domain)
  if (!domain) {
    domain = await getMaster()
  }
  if (!domain) {
    domain = app.globalData.baseUrl
  }
  // console.log(requestUrl)
  ajaxTimes++
  let header
  if (token) {
    header = {
        'content-type':'application/json',
        'XX-Token': token,
        'XX-Device-Type': 'wxapp'
    }
  } else {
    header = {
        'content-type':'application/json'
    }
  }
  if(params.method==='POST'){
    header = {
      'content-type':'application/x-www-form-urlencoded',
    }
    if (params.url.indexOf('?') != -1) {
      params.url = params.url + '&version=' + app.globalData.version + '&devicetype=' + app.globalData.devicetype
    } else {
      params.url = params.url + '?version=' + app.globalData.version + '&devicetype=' + app.globalData.devicetype
    }
  } else if (params.method == 'GET') {
    params.data.version = app.globalData.version 
    params.data.devicetype = app.globalData.devicetype 
  }
//   console.log(params.url)
  if (!params.hideLoading) {
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
  }
  return new Promise((resovle,reject)=>{
    // console.log(params);
    wx.request({
      ...params,
      header:header,
      url:domain+params.url,
      success:(result)=>{
        resovle(result.data)
      },
      fail:(err)=>{
        reject(err)
      },
      complete:()=>{
        ajaxTimes--
        if(ajaxTimes===0){
          wx.hideLoading()
        }
      }
    });
  })
}

function getMaster () {
  return new Promise (resolve => {
    wx.request({
      url: app.globalData.baseUrl + 'api/wxapp/public/master',
      header:{
        'content-type':'application/json'
      },
      data: {},
      success:(result)=>{
        if (result && result.data.code == 1) {
          app.globalData.domain = result.data.data.domain
          resolve(result.data.data.domain)
        }
      },
      fail:(err)=>{
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete:()=>{
      }
    })
  })
}

export const requestWrap=(reuslt, noToast)=>{
  if(reuslt.code==1){
    return reuslt
  } else if(reuslt.code==10001){
    if (!noToast) {
      wx.showToast({
        title: reuslt.error,
        icon:'none',
        duration:2000
      });
    }
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('student')
    wx.removeStorageSync('openid')
    wx.removeStorageSync('token')
} else {
    wx.showToast({
      title: reuslt.error,
      icon:'none',
      duration:2000
    });
    return reuslt;
  }
}

import {login, getUserProfile} from "../utils/asyncWx.js"
export const checkLogin = async (url, page) => {
    const wxUserInfo = await getUserProfile()
    const res = await login()
    let ret = requestWrap(await request({
        url:"api/wxapp/public/login",
        method:'GET',
        data: {
            code: res.code,
            encrypted_data: wxUserInfo.encryptedData,
            iv: wxUserInfo.iv,
            raw_data: JSON.stringify(wxUserInfo.rawData),
            signature: wxUserInfo.signature
        }
    }))
    return new Promise((resolve, reject) => {
        // console.log(ret)
        if (ret && ret.code == 1) {
            ret.data.user.is_complete = ret.data.is_complete
            wx.setStorageSync('openid', ret.data.openid)
            wx.setStorageSync('token', ret.data.token)
            wx.setStorageSync('userInfo', ret.data.user)
            // resolve(ret)
            resolve(true)
            if (ret.data.is_complete == 0) {
                wx.navigateTo({
                    url: '/pages/login/login',
                })
            } else {
                if (url) {
                    wx.navigateTo({
                        url
                    })
                } else {
                    if (page === 'index') {
                        wx.showToast({
                            title: '请选择学生',
                            icon: 'none'
                        })
                    } else {
                        wx.showToast({
                            title: '登录成功',
                            icon: 'none'
                        })
                    }
                }
            }
        } else {
            wx.showToast({
                title: result.error,
                icon: 'none'
            })
        }
    })
}


